import React, { Component, createContext } from 'react'

const TestContext = createContext()
const {Provider, Consumer} = TestContext
export default class Father extends Component {
  state = {
    message: '父组件消息'
  }
  render() {
    const { message } = this.state
    return (
      <div>
        父组件：{message}
        <Provider value={message}>
          <Child />
        </Provider>
      </div>
    )
  }
}

class Child extends Component {
  render() {
    return (
      <div>
        子组件
        <GrandChildA />
        <GrandChildB />
      </div>
    )
  }
}

class GrandChildA extends Component {
  // 类式组建独有的方式; static声明接收context
	static contextType = TestContext
  render() {
    const message = this.context
    return (
      <div>
        子孙组件A的: {message}
      </div>
    )
  }
}

function GrandChildB() {
  // 函数式组件(类式组建同样适用)的使用方式：Consumer组件，会传递一个回调，参数就是提供的context
  return (
    <div>
      <Consumer>
        { value => <div>子孙组件B中的: {value}</div> }
      </Consumer>
    </div>
  )
}



